package com.coolxiaoyoa.donwload;

import io.netty.channel.*;
import io.netty.handler.codec.http.*;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.RandomAccessFile;

/**
 * @author Kerry on 18/09/29
 */


public class HttpDownloadServerHandler extends ChannelInboundHandlerAdapter {

    private final MainController mainController;

    public HttpDownloadServerHandler(MainController mainController) {
        this.mainController = mainController;
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if (!(msg instanceof FullHttpRequest)) {
            return;
        }
        FullHttpRequest request = (FullHttpRequest) msg;
        System.out.println(request);

        if (!request.decoderResult().isSuccess()) {
            return;
        }

        File file = new File("E:\\BaiduNetdiskDownload\\金秘书为何这样\\[TSKS][Why.Secretary.Kim][E001(720P)][KO_CN].mkv");
        if (!file.exists()) {
            return;
        }

        DefaultHttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);


        RandomAccessFile raf = new RandomAccessFile(file, "r");
        long fileLength = raf.length();
        HttpUtil.setContentLength(response, raf.length());
        MimetypesFileTypeMap m = new MimetypesFileTypeMap();


        String contentType = m.getContentType(file.getPath());
        if (!"application/octet-stream".equals(contentType)) {
            contentType += ";charset=utf-8";
        }

        response.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType);
        response.headers().set(HttpHeaderNames.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());
//        QueryStringDecoder params = new QueryStringDecoder(request.uri());


        System.out.println("响应结果如下：");
        System.out.println(response);

        ctx.write(response);
//        ctx.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise());
        ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());

        ChannelFuture channelFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        if (request.protocolVersion().isKeepAliveDefault()) {
            channelFuture.addListener(ChannelFutureListener.CLOSE);
        }
    }
}
